import React, { useEffect } from 'react';
import styles from './index.less';
import { Button, message, Space, Tabs } from 'antd';
import { LockOutlined } from '@ant-design/icons';
import lock from '@/assets/lock.svg';
import { PlanPage } from './planPage';
import _ from 'lodash';
import WindowPeriodConfiguration from '../components/WindowPeriodConfiguration';
import LimitQuery from '../components/limitQuery';
import OrderStatus from '../components/orderStatus';
import { DeleteOutlined, PlusOutlined, UploadOutlined } from '#/utils/antdIcons';
import { connect } from 'umi';
import { TRAlert } from '#/components';
import {
  cancleTimeTaskDeclaration,
  createTimeTaskDeclaration,
  deleteProgramInfo,
  immediateDeclaration,
  queryPlanInfo,
  saveStrategy,
} from '../services';
import { buildSaveData, getEditDisabled, judgeSave, TimeFrameArr } from '../helper';
import { HttpCode } from '#/utils/contacts';
import { exportMoreSheet } from '@/utils/fileExport.js';
import { useSetState } from 'ahooks';
import moment from 'moment';
import { ELECTRIC_ENERGY_OPTIONS, ELECTRIC_PRICE_OPTIONS } from '../constant';

const btnStyle = { height: 20, width: 60 };

const Plan = ({
  planData,
  dispatch,
  activeKey,
  currentUser,
  type,
  date,
  provinceId,
  editDisabled,
  hourOrder,
  sitelist,
  marketList,
  setLoading,
  originalData,
  marketId,
}) => {
  const [state, setState] = useSetState({
    open: false,
    time: moment(),
  });

  useEffect(() => {
    const editDisabled = getEditDisabled(planData, activeKey);
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        editDisabled,
      },
    });
  }, [activeKey]);

  const changeActiveKey = (key) => {
    if (key !== '9999') {
      dispatch({
        type: 'interprovincialSpotDeclaration/setState',
        payload: {
          activeKey: key,
        },
      });
    } else if (key === '9999') {
      const username = currentUser.name;
      let lastBbj = {};
      const data = _.cloneDeep(planData);
      data.forEach((i) => {
        if (i.userId === currentUser.personId) {
          lastBbj = i;
        }
      });
      let index = 1;
      if (lastBbj.title) {
        index = lastBbj.title.replace(username, '') * 1 + 1;
      }
      data.push({
        title: username + index,
        userId: currentUser.personId,
        strategyList: [],
      });
      const activeKey = (data.length - 1).toString();
      dispatch({
        type: 'interprovincialSpotDeclaration/setState',
        payload: {
          planData: data,
          activeKey,
        },
      });
    }
  };

  const handleSave = async () => {
    let data = planData[+activeKey] || {};
    data.dayTpye = type;
    data.reportDate = date;
    data.marketId = marketId;
    data.provinceId = provinceId;
    data.programmeId = data.programmeId || null;
    data = buildSaveData(data, type, date);
    if (judgeSave(data)) {
      return;
    }
    setLoading(true);
    const res = await saveStrategy(data);
    if (res?.statusCode === HttpCode.SUCCESS) {
      message.success('保存成功');
      dispatch({
        type: 'interprovincialSpotDeclaration/setState',
        payload: {
          hasSave: true,
        },
      });
    } else {
      setLoading(false);
      message.error(res.message || '保存失败');
    }
  };

  const deletePlan = async (e, index) => {
    e.stopPropagation();
    const res = await TRAlert.show('当前方案信息即将被删除,是否继续');
    if (res.index === 1) {
      const data = planData?.[+index] || {};
      if (data.programmeId) {
        setLoading(true);
        const res = await deleteProgramInfo([data.programmeId]);
        if (res.statusCode === HttpCode.SUCCESS) {
          message.success('删除成功');
          dispatch({
            type: 'interprovincialSpotDeclaration/setState',
            payload: {
              hasSave: true,
            },
          });
        } else {
          setLoading(false);
          message.error(res.message || '删除失败');
        }
      } else {
        let plan = _.cloneDeep(planData);
        plan.splice(index, 1);
        const activeKey = (plan.length - 1).toString();
        dispatch({
          type: 'interprovincialSpotDeclaration/setState',
          payload: {
            planData: plan,
            activeKey,
          },
        });
      }
    }
  };

  const deleteIcon = (index) => {
    return (
      <DeleteOutlined
        style={{ color: 'rgba(235, 87, 87, 1)', marginLeft: 5 }}
        onClick={(e) => deletePlan(e, index)}
      />
    );
  };
  const exportFile = () => {
    if (!!planData[+activeKey] && planData[+activeKey]?.strategyList.length > 0) {
      let sheets = [];
      let columns = [
        { header: '标的日', key: 'markDate', width: '14' },
        {
          header: '交易单元',
          key: 'stationName',
          width: '14',
        },
        { header: '限额条件', key: 'limitName', width: '28' },
        {
          header: '时间段',
          key: 'times',
          width: '12',
        },
        { header: '阶梯段', key: 'step', width: '10' },
        {
          header: '电力',
          key: 'electric',
          width: '14',
        },
        { header: '电价', key: 'price', width: '10' },
      ];
      planData[+activeKey]?.strategyList.map((item, index) => {
        let sheet = {
          columns: [...columns],
          title: item.strategyName,
          data: [],
          myMerges: [],
          mergeIndex: [4],
        };
        let stationName = [];
        sitelist.map((item1) => {
          item1.children.map((item2) => {
            if (item.stationIds.includes(item2.value)) {
              stationName.push(item2.label);
            }
          });
        });
        let limitName =
          ELECTRIC_ENERGY_OPTIONS[item.electricEnergy - 1].label +
          ' , ' +
          (item.electricPriceType !== 3
            ? ELECTRIC_PRICE_OPTIONS[item.electricPriceType - 1].label
            : ELECTRIC_PRICE_OPTIONS[item.electricPriceType - 1].label + ': ' + item.electricPrice);
        let stepIndex = null;
        let details = item.details || [];
        if (type === 'intraday') {
          const arr = [];
          details?.map((i) => {
            if (i.strategyType === 2) {
              i?.children.forEach((a) => {
                arr.push(a);
              });
              details = arr;
            } else if (i.strategyType === 3) {
              i?.children.forEach((a) => {
                a?.children?.forEach((b) => {
                  arr.push({ ...b, timePeriod: a.timePeriod });
                });
              });
              details = arr;
            }
          });
        }
        details.map((item1, index) => {
          let obj = {};
          obj = {
            markDate: type === 'intraday' ? date : item.markDate,
            stationName: stationName.join(','),
            limitName: limitName,
            step: item1.step || null,
            times: item1.timePeriod,
            electric: item1.electric,
            price: item1.price,
          };
          let myMerge = null;
          if (item1.step == 1 || item1.step == null) {
            if (stepIndex != null) {
              myMerge = [stepIndex + 3, 4, index + 2, 4];
            }
            stepIndex = !!item1.step ? index : null;
          }
          if (myMerge != null) {
            sheet.myMerges.push(myMerge);
          }
          sheet.data.push(obj);
        });
        if (sheet.myMerges.length < 1) {
          sheet.columns.splice(4, 1);
        }
        sheets.push(sheet);
      });
      let file_name = '';
      marketList.map((item) => {
        if (item.value == marketId) {
          file_name = item.label + date + (type === 'dayahead' ? '日前申报' : '日内申报');
        }
      });
      exportMoreSheet(sheets, file_name);
    } else {
      message.error('暂无数据可以导出！');
    }
  };
  const handleDeclare = async (declareType = 0, time) => {
    let data = planData?.[+activeKey] || {};
    //  申报的逻辑修改为先保存 -> 查询 ->申报
    data.dayTpye = type;
    data.reportDate = date;
    data.marketId = marketId;
    data.provinceId = provinceId;
    data.programmeId = data?.programmeId || null;
    data = buildSaveData(data, type, date);
    if (judgeSave(data)) {
      return;
    }
    setLoading(true);
    const res = await saveStrategy(data);
    if (res?.statusCode === HttpCode.SUCCESS) {
      const saveRes = await queryPlanInfo({
        provinceId: provinceId,
        hourOrder: '',
        marketId,
        type: type,
        date,
      });
      if (saveRes.statusCode === HttpCode.SUCCESS) {
        const saveData = saveRes?.dataList?.[+activeKey] || {};
        await onDeclareServer(declareType, time, saveData);
      } else {
        setLoading(false);
      }
    } else {
      setLoading(false);
      message.error(res.message || '保存失败');
    }
  };

  const onDeclareServer = async (declareType, time, data) => {
    const service = declareType ? createTimeTaskDeclaration : immediateDeclaration;
    const params = {
      programmeId: data.programmeId,
    };
    //declareType为0时为立即申报，为1时为定时申报
    params.type = declareType;
    if (!declareType && type === 'intraday') {
      let timeOrder = data?.strategyList?.[0]?.['hourOrderList']?.toString() || '';
      timeOrder = TimeFrameArr.filter((i) => i.label === timeOrder)?.[0]?.['order'] || '';
      params.timeOrder = timeOrder;
    }
    setLoading(true);
    const res = await service(params);
    if (res && res?.statusCode === HttpCode.SUCCESS) {
      message.success('申报成功');
    } else {
      setLoading(false);
      message.error(res?.message || '申报失败');
    }
    dispatch({
      type: 'interprovincialSpotDeclaration/setState',
      payload: {
        hasSave: true,
      },
    });
  };

  // 撤销定时申报
  const handleCancelDeclare = async () => {
    const res = await TRAlert.show('请确认是否撤回当前方案定时申报?');
    if (res.index === 1) {
      setLoading(true);
      const programmeId = planData?.[+activeKey]?.programmeId;
      const res = await cancleTimeTaskDeclaration({
        programmeId,
      });
      if (res && res?.statusCode === HttpCode.SUCCESS) {
        message.success('撤回成功!');
        dispatch({
          type: 'interprovincialSpotDeclaration/setState',
          payload: {
            hasSave: true,
          },
        });
      } else {
        setLoading(false);
        message.error(res?.message || '撤回失败');
      }
    }
  };

  const _lockEl = () => {
    return (
      <div
        onClick={handleCancelDeclare}
        style={{
          display: 'flex',
          alignItems: 'center',
        }}
      >
        {/* <img src={lock} alt={''} /> */}
        <LockOutlined
          style={{ width: '16px', height: '16px', color: 'var(--font-active) !important' }}
        />
        <span style={{ marginLeft: 10 }}>定时申报</span>
      </div>
    );
  };

  const findIsManyDays = (data) => {
    const strategyList = data?.strategyList || [];
    let isManyDays = false;
    strategyList.forEach((i) => {
      const arr = i?.markDate?.split(',') || [];
      if (arr.length > 1) {
        isManyDays = true;
      }
    });
    return isManyDays;
  };

  const intraDayFindIsManyDays = (data) => {
    if (date) {
      const time = date?.split(',');
      if (time[0] !== time[1]) {
        return true;
      }
    }
    const strategyList = data?.strategyList || [];
    let isManyDays = false;
    let order = strategyList?.[0]?.hourOrderList?.[0] || '-1';
    strategyList.forEach((i) => {
      const str = i?.hourOrderList?.[0]?.toString() | '';
      if (str !== order) {
        isManyDays = true;
      }
      if (i?.hourOrderList?.length > 1) {
        isManyDays = true;
      }
    });
    return isManyDays;
  };

  const getDeclareDisabled = () => {
    // 不是自己的不能申报
    const disabled = editDisabled;
    const data = planData[+activeKey];
    let isManyDays;
    if (type === 'dayahead') {
      // 日前的情况下标的日存在多日不能申报
      isManyDays = findIsManyDays(data);
    } else {
      // 日内情况下时段选择多时段、多策略不是同一时段或查询选择多日不能申报
      isManyDays = intraDayFindIsManyDays(data);
    }
    return disabled || isManyDays;
  };

  return (
    <div className={styles.tabs}>
      <Tabs
        activeKey={activeKey}
        onChange={changeActiveKey}
        destroyInactiveTabPane={true}
        tabBarExtraContent={{
          right: (
            <Space>
              <WindowPeriodConfiguration />
              <LimitQuery />
              <OrderStatus />
              <Button onClick={handleSave} disabled={editDisabled}>
                保存
              </Button>
              <Button onClick={() => handleDeclare(0)} disabled={getDeclareDisabled()}>
                立即申报
              </Button>
              {planData?.[+activeKey]?.timelyTime ? (
                <Button type={'primary'}>{_lockEl()}</Button>
              ) : (
                <Button type={'primary'} onClick={() => handleDeclare(1)} disabled={editDisabled}>
                  定时申报
                </Button>
              )}
              <Button type="link" icon={<UploadOutlined />} onClick={exportFile}>
                导出
              </Button>
            </Space>
          ),
        }}
      >
        {planData &&
          planData?.map((i, k) => (
            <Tabs.TabPane
              tab={
                <div>
                  {i.title}
                  {!getEditDisabled(planData, k) && deleteIcon(k)}
                </div>
              }
              key={'' + k}
            >
              <PlanPage disabled={editDisabled} strategyList={i.strategyList || []} />
            </Tabs.TabPane>
          ))}
        <Tabs.TabPane
          tab={
            // <div style={{ color: 'rgba(24, 160, 251, 1)' }}>
            //   <PlusOutlined style={{ marginRight: 5 }} /> 新增
            // </div>
            <Button type="link" icon={<PlusOutlined />} style={{ padding: 0 }}>
              新增
            </Button>
          }
          key="9999"
        />
      </Tabs>
    </div>
  );
};

export default connect(({ global, interprovincialSpotDeclaration }) => ({
  currentUser: global.configure.currentUser,
  planData: interprovincialSpotDeclaration.planData,
  activeKey: interprovincialSpotDeclaration.activeKey,
  type: interprovincialSpotDeclaration.type,
  date: interprovincialSpotDeclaration.date,
  provinceId: interprovincialSpotDeclaration.provinceId,
  editDisabled: interprovincialSpotDeclaration.editDisabled,
  hourOrder: interprovincialSpotDeclaration.hourOrder,
  sitelist: interprovincialSpotDeclaration.sitelist,
  marketList: interprovincialSpotDeclaration.marketList,
  originalData: interprovincialSpotDeclaration.originalData,
  marketId: interprovincialSpotDeclaration.marketId,
}))(Plan);
